package com.tsq.sms.provider.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.common.collect.ImmutableMap;
import com.tsq.common.model.ResponseData;
import com.tsq.sms.api.dto.SmsDTO;
import com.tsq.sms.provider.builder.SmsBuilder;
import com.tsq.sms.provider.service.SmsService;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * @author Tango
 * @since 2020/8/24
 */

@Service
@Slf4j
@ConfigurationProperties(prefix = "sms")
@Setter
public class SmsServiceImpl implements SmsService {

    private String version;
    private String domain;
    private String region;
    private String accessKeyId;
    private String accessSecret;
    private Map<String, String> templates;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String REDIS_PREFIX = "user:token:sms:";

    @PostConstruct
    public void init() {
        client = new DefaultAcsClient(DefaultProfile.getProfile(region, accessKeyId, accessSecret));
    }


    private IAcsClient client;

    public ResponseData<SmsDTO> login(SmsDTO smsDTO) {
        //TODO 校验 多号码
        String phoneNumbers = smsDTO.getPhoneNumbers();
        if (StringUtils.isNotBlank(phoneNumbers)) {
            String random = String.valueOf(RandomUtil.randomInt(121212, 989898));
            smsDTO.setTemplateParams(JSON.toJSONString(ImmutableMap.of("code", random)));
            boolean result = to(smsDTO);
            if (result) {
                redisTemplate.opsForValue().set(REDIS_PREFIX + phoneNumbers, random);
                return ResponseData.success();
            }
        }
        return ResponseData.error();
    }

    @Override
    public ResponseData<SmsDTO> smsTo(SmsDTO smsDTO) {
        return to(smsDTO) ? ResponseData.success() : ResponseData.error();
    }


    @Override
    public ResponseData<SmsDTO> smsMass(SmsDTO smsDTO) {
        return ResponseData.error();
    }


    public boolean to(SmsDTO smsDTO) {
        CommonRequest commonRequest = SmsBuilder.init(version, domain, region)
                .sign(smsDTO.getSignName())
                .template(templates.get(smsDTO.getTemplateName()))
                .param(smsDTO.getTemplateParams())
                .to(smsDTO.getPhoneNumbers())
                .build();
        try {
            CommonResponse commonResponse = client.getCommonResponse(commonRequest);
//           验证码放到redis  key的格式： user:token:sms:username
            redisTemplate.opsForValue().set(REDIS_PREFIX + smsDTO.getPhoneNumbers(), smsDTO.getTemplateParams());
            System.out.println(commonResponse.getData());
            return true;
        } catch (ClientException e) {
            e.printStackTrace();
            return false;
        }
    }

}
